package helper

import (
	"crypto/md5"
	"fmt"

	"github.com/golang-jwt/jwt/v5"
)

func GetMd5(s string) string {
	return fmt.Sprintf("%x", md5.Sum([]byte(s)))
}

type UserClaim struct {
	Identity string `json:"identity"`
	Name     string `json:"name"`
	jwt.RegisteredClaims
}

var myKey = []byte("gin-gorm-key")

func GenerateToken(identity, name string) (string, error) {
	userClaim := &UserClaim{
		Identity:         identity,
		Name:             name,
		RegisteredClaims: jwt.RegisteredClaims{},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, userClaim)
	tokenString, err := token.SignedString(myKey)
	if err != nil {
		return "", err
	}
	return tokenString, nil
}

func AnalyseToken(tokenString string) (*UserClaim, error) {
	parsedToken, err := jwt.ParseWithClaims(tokenString, &UserClaim{}, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return myKey, nil
	})
	if err != nil {
		return nil, err
	}
	if claims, ok := parsedToken.Claims.(*UserClaim); ok && parsedToken.Valid {
		return claims, nil
	} else {
		return nil, fmt.Errorf("analyse token error: %v", err)
	}
}
